package com.lijian.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lijian.mapper.MenuMapper;
import com.lijian.mapper.TypeMapper;
import com.lijian.pojo.Menu;
import com.lijian.pojo.MenuResult;
import com.lijian.pojo.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private TypeMapper typeMapper;

    @GetMapping
    public MenuResult findAll(@RequestParam Integer page, @RequestParam Integer limit) {
        IPage<Menu> menuIPage = menuMapper.selectPage(new Page<>(page, limit), null);
        List<Menu> menus = menuIPage.getRecords();
        menus.forEach(menu -> {
            Type type = typeMapper.selectById(menu.getTypeId());
            menu.setType(type);
        });
    
        Integer total = Math.toIntExact(menuIPage.getTotal());

        return new MenuResult(0, "成功", total, menus);
    }
    // @sukai-cheng的修改
    // @GetMapping("/findAll/{index}/{limit}")
    // public MenuVO findAll(@PathVariable("index") int index, @PathVariable("limit") int limit) {
    //     index = (index-1)*limit;
    //     return new MenuVO(0,"",menuMapper.selectCount(null),menuMapper.findAll(index,limit));
    // }

    @DeleteMapping("/deleteById/{id}")
    public void deleteMenuById(@PathVariable Integer id){
        menuMapper.deleteById(id);
    }

    @GetMapping("/findTypes")
    public List<Type> findTypes(){
        return typeMapper.selectList(null);
    }

    @GetMapping("/findType/{id}")
    public Type findTypeById(@PathVariable Integer id){
        return typeMapper.selectById(id);
    }

    @PostMapping("/save")
    public void saveMenu(@RequestBody Menu menu){
        menu.setTypeId(menu.getType().getId());
        menuMapper.insert(menu);
    }

    @GetMapping("/findById/{id}")
    public Menu findById(@PathVariable Long id){
        return menuMapper.selectById(id);
    }

    @PutMapping("/update")
    public void update(@RequestBody Menu menu){
        menuMapper.updateById(menu);
    }
}
